package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author ZTtv
 * @date 2025-09-01
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Value("deviceMaintainerRole")
    private String deviceMaintainerRole;
    @Value("managerRole")
    private String managerRole;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void alertFilter() {
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if(count<=0){
            return;
        }
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if(CollUtil.isEmpty( values)){
            return;
        }
        List<DeviceData> deviceDatas=new ArrayList<>();
        values.forEach(value -> {
            deviceDatas.addAll(JSONUtil.toList(value.toString(),DeviceData.class));
        });
        deviceDatas.forEach(this::alertFilter);
    }

    private void alertFilter(DeviceData deviceData) {
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(between>60){
            return;
        }
        List<AlertRule> allRules = list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, "-1"));
        List<AlertRule> rules = list(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, deviceData.getIotId()));
        allRules.addAll(rules);
        if(CollUtil.isEmpty(allRules)){
            return;
        }
        allRules.forEach(rule -> {
            deviceDataAlertHandler(rule,deviceData);
        });
    }

    private void deviceDataAlertHandler(AlertRule rule, DeviceData deviceData) {
        String[] split = rule.getAlertEffectivePeriod().split("~");
        LocalTime startTime=LocalTime.parse(split[0]);
        LocalTime endTime=LocalTime.parse(split[1]);
        LocalTime localTime = deviceData.getAlarmTime().toLocalTime();
        if(localTime.isBefore(startTime)||localTime.isAfter(endTime)){
            return;
        }
        String iotId = deviceData.getIotId();
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        Double value = rule.getValue();
        Double deviceDataValue = Double.valueOf(deviceData.getDataValue());
        int compare= NumberUtil.compare(deviceDataValue, value);
        if(">=".equals(rule.getOperator())&&compare>0||"<".equals(rule.getOperator())&&compare<0){
            log.info("当前上报的数据符合规则异常");
        }
        else {
            redisTemplate.delete(aggCountKey);
            return;
        }
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        String  silentTime =(String) redisTemplate.opsForValue().get(silentKey);
        if(StringUtils.isNotEmpty(silentTime)){
            return;
        }
        String aggCount =(String) redisTemplate.opsForValue().get(aggCountKey);
        int count=StringUtils.isEmpty(aggCount)?1:Integer.parseInt(aggCount)+1;
        if (ObjectUtil.notEqual(count, rule.getDuration())) {
            // 不相等
            redisTemplate.opsForValue().set(aggCountKey, count + "");
            return;
        }
        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(silentKey,"1", rule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        List<Long> userIds=new ArrayList<>();
        if (rule.getAlertDataType().equals(0)) {
            // 老人异常数据
            if (deviceData.getLocationType().equals(0)) {
                // 说明是报警手表，直接可以找到老人的id,通过老人id,找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)) {
                // 说明是床位设备，可以通过床位id找到老人，通过老人id,找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            // 设备异常数据，找维修工，或者是行政人员
            userIds = userRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }
        // 不论是哪种情况，都要通知超级管理员
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        // 去重
        allUserIds = CollUtil.distinct(allUserIds);

        // 保存报警数据
        // 批量保存异常数据
        List<AlertData> alertDataList = insertAlertData(allUserIds, rule, deviceData);

        // websocket推送消息
        webSocketNotity(alertDataList.get(0), rule, allUserIds);
    }
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * websocket推送消息
     * @param alertData
     * @param rule
     * @param allUserIds
     */
    private void webSocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, allUserIds);

    }

    /**
     * 保存报警数据
     *
     * @param allUserIds
     * @param rule
     * @param deviceData
     */
    private  List<AlertData> insertAlertData(Collection<Long> allUserIds, AlertRule rule, DeviceData deviceData) {
        // 对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        // 心率<60,持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(rule.getAlertDataType());
        // 遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        // 批量保存
        alertDataService.saveBatch(list);
        return list;

    }
}
